import axios from "axios";
import config  from "./config";
import router  from '../router'
import { ElMessage } from "element-plus";

export default function request(options) {
    return new Promise((resolve,reject) =>{
        const instance=axios.create({
            ...config
        })

        //request 请求拦截器
        instance.interceptors.request.use(
            (config) =>{
                let token = localStorage.getItem("pm_token");
                //发送请求时携带token
                if(token){
                    config.headers.token = token;
                }else{
                    router.push("/login");
                }
                return config;
            },
            (error)=>{
                //请求发生错误时
                console.log("request:",error);
                //判断请求超时
                if(
                    error.code === "ECONNABORTED" &&
                    error.message.indexOf("timeout") !== -1
                ){
                    ElMessage({
                        message:"请求超时",
                        type:"error",
                        showClose:true
                    });
                }
                return Promise.reject(error);
            }
        );

        instance(options)
        .then((res) =>{
            // 200 成功/-1失败，网络异常/-2登录失效跳回登录
            if(res.code ===200){
                resolve(res);
            }else{
                //未登录
                if(res.code === -2){
                    router.push("/login");
                }
                ElMessage({
                    message:res.msg || "操作失败",
                    type:"error",
                    showClose:true
                });
                reject(res);
            }
        })
        .catch((error)=>{
            reject(error);
        })
    })
}